package com.ibm.testbed.script.adjust;

import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbenchPart;

public class TestbedPartListener implements IPartListener {

	@Override
	public void partActivated(IWorkbenchPart part) {

		IDocument document = this.getDocument(part);
		if (document != null)
			attacheToDocument(document);

	}

	@Override
	public void partBroughtToTop(IWorkbenchPart part) {

	}

	@Override
	public void partClosed(IWorkbenchPart part) {

	}

	@Override
	public void partDeactivated(IWorkbenchPart part) {

		IDocument document = this.getDocument(part);
		if (document != null)deattacheFromDocument(document);
		
	}

	@Override
	public void partOpened(IWorkbenchPart part) {

	}

	public void attacheToDocument(IDocument document) {

		document.addDocumentListener(TestbedDocumentListener.INSTANCE);
	}

	public void deattacheFromDocument(IDocument document) {

		document.removeDocumentListener(TestbedDocumentListener.INSTANCE);

	}

	public IDocument getDocument(IWorkbenchPart part) {

		if (part instanceof CompilationUnitEditor) {

			CompilationUnitEditor editor = (CompilationUnitEditor) part;
			return editor.getDocumentProvider().getDocument(
					editor.getEditorInput());

		}

		return null;

	}

}
